package com.clippick.database;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.database.Cursor;
import android.util.Log;

import com.clippick.api.GetDataFromApi;
import com.clippick.common.GlobalValue;
import com.clippick.common.Utils;

@SuppressWarnings("rawtypes")
public class ClipData {
	/** 별 DB만 가져와서 List<Map> 형식으로 리턴 */
	public static List<Map> fetchStarClipFromDb(HistoryDBAdapter dbManager,
			FeedOrderDBAdapter orderManager) {
		// set return list<Map>
		List<Map> result = new ArrayList<Map>();

		// fetch all the clips stored at local database
		Cursor dbCursor = dbManager.fetchStarFeedOrderByDescDate("1");
		if (dbCursor.moveToFirst()) {
			do {
				Map<String, String> m = new HashMap<String, String>();
				m.put(HistoryDBAdapter.KEY_DB_NO, dbCursor.getString(dbCursor
						.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_NO)));
				m.put(HistoryDBAdapter.KEY_DB_DEVICE,
						dbCursor.getString(dbCursor
								.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_DEVICE)));
				m.put(HistoryDBAdapter.KEY_DB_DATE, dbCursor.getString(dbCursor
						.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_DATE)));
				m.put(HistoryDBAdapter.KEY_DB_KEEPBOX,
						dbCursor.getString(dbCursor
								.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_KEEPBOX)));
				m.put(HistoryDBAdapter.KEY_DB_TEXT, dbCursor.getString(dbCursor
						.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_TEXT)));
				m.put(HistoryDBAdapter.KEY_DB_CONTENTS,
						dbCursor.getString(dbCursor
								.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_CONTENTS)));
				m.put(HistoryDBAdapter.KEY_DB_IMG, dbCursor.getString(dbCursor
						.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_IMG)));

				Cursor imgCursor = orderManager
						.fetchFeedByIndexOrderDesc(Long.parseLong(m.get(
								HistoryDBAdapter.KEY_DB_NO).toString()));
				if (imgCursor.moveToFirst()) {
					do {
						m.put(FeedOrderDBAdapter.KEY_DB_IMAGE_URL,
								imgCursor.getString(imgCursor
										.getColumnIndexOrThrow(FeedOrderDBAdapter.KEY_DB_IMAGE_URL)));
						m.put(FeedOrderDBAdapter.KEY_DB_TEXT_PATH,
								imgCursor.getString(imgCursor
										.getColumnIndexOrThrow(FeedOrderDBAdapter.KEY_DB_TEXT_PATH)));
						m.put(FeedOrderDBAdapter.KEY_DB_ORDER,
								imgCursor.getString(imgCursor
										.getColumnIndexOrThrow(FeedOrderDBAdapter.KEY_DB_ORDER)));

					} while (imgCursor.moveToNext());
				}
				// close imgCursor
				imgCursor.close();

				// add clip items into result
				result.add(m);
			} while (dbCursor.moveToNext());
		}

		// close dbCursor
		dbCursor.close();
		return result;
	}

	/** DB에서 데이터를 가져와서 List<Map> 형식으로 리턴 */
	public static List<Map> fetchClipFromDb(HistoryDBAdapter dbManager,
			FeedOrderDBAdapter orderManager) {
		// set return list<Map>
		List<Map> result = new ArrayList<Map>();

		// fetch all the clips stored at local database
		Cursor dbCursor = dbManager.fetchFeedAllOrderByDescDate();
		if (dbCursor.moveToFirst()) {
			do {
				Map<String, String> m = new HashMap<String, String>();
				m.put(HistoryDBAdapter.KEY_DB_NO, dbCursor.getString(dbCursor
						.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_NO)));
				m.put(HistoryDBAdapter.KEY_DB_DEVICE,
						dbCursor.getString(dbCursor
								.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_DEVICE)));
				m.put(HistoryDBAdapter.KEY_DB_DATE, dbCursor.getString(dbCursor
						.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_DATE)));
				m.put(HistoryDBAdapter.KEY_DB_KEEPBOX,
						dbCursor.getString(dbCursor
								.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_KEEPBOX)));
				m.put(HistoryDBAdapter.KEY_DB_TEXT, dbCursor.getString(dbCursor
						.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_TEXT)));
				m.put(HistoryDBAdapter.KEY_DB_CONTENTS,
						dbCursor.getString(dbCursor
								.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_CONTENTS)));
				m.put(HistoryDBAdapter.KEY_DB_IMG, dbCursor.getString(dbCursor
						.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_IMG)));

				Cursor imgCursor = orderManager
						.fetchFeedByIndexOrderDesc(Long.parseLong(m.get(
								HistoryDBAdapter.KEY_DB_NO).toString()));
				if (imgCursor.moveToFirst()) {
					do {
						m.put(FeedOrderDBAdapter.KEY_DB_IMAGE_URL,
								imgCursor.getString(imgCursor
										.getColumnIndexOrThrow(FeedOrderDBAdapter.KEY_DB_IMAGE_URL)));
						m.put(FeedOrderDBAdapter.KEY_DB_TEXT_PATH,
								imgCursor.getString(imgCursor
										.getColumnIndexOrThrow(FeedOrderDBAdapter.KEY_DB_TEXT_PATH)));
						m.put(FeedOrderDBAdapter.KEY_DB_ORDER,
								imgCursor.getString(imgCursor
										.getColumnIndexOrThrow(FeedOrderDBAdapter.KEY_DB_ORDER)));

					} while (imgCursor.moveToNext());
				}
				// close imgCursor
				imgCursor.close();

				// add clip items into result
				result.add(m);
			} while (dbCursor.moveToNext());
		}

		// close dbCursor
		dbCursor.close();
		return result;
	}

	public static Map<Object, Object> compareFeed(HistoryDBAdapter dbManager) {
		Map<Object, Object> item = new HashMap<Object, Object>();

		List<Map<?, String>> changedList = new ArrayList<Map<?, String>>();
		List<Map<?, String>> newList = new ArrayList<Map<?, String>>();
		List<Map<?, String>> removedList = new ArrayList<Map<?, String>>();

		Cursor c1= dbManager.findRemovedFeeds();
		if (c1.moveToFirst()) {
			do {
				Map<Object, String> m = new HashMap<Object, String>();
				m.put(HistoryDBAdapter.KEY_DB_NO, c1.getString(c1
						.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_NO)));
				removedList.add(m);
			} while (c1.moveToNext());
		}

		Cursor c2 = dbManager.findChangedFeeds();
		if (c2.moveToFirst()) {
			do {
				Map<Object, String> m = new HashMap<Object, String>();
				m.put(HistoryDBAdapter.KEY_DB_NO, c2.getString(c2
						.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_NO)));
				changedList.add(m);
			} while (c2.moveToNext());
		}

		Cursor c3 = dbManager.findNewFeeds();
		if (c3.moveToFirst()) {
			do {
				Map<Object, String> m = new HashMap<Object, String>();
				m.put(HistoryDBAdapter.KEY_DB_NO, c3.getString(c3
						.getColumnIndexOrThrow(HistoryDBAdapter.KEY_DB_NO)));
				newList.add(m);
			} while (c3.moveToNext());
		}

		c1.close();
		c2.close();
		c3.close();

		item.put("changed", changedList);
		item.put("new", newList);
		item.put("removed", removedList);

		dbManager.deleteTempFeedAll();

		return item;
	}

	/** 이미지와 텍스트가 포함된 데이터를 재정의 */
	@SuppressWarnings("unchecked")
	public static List<Map> getClipData(List<Map> newFeed) {
		List<Map> result = new ArrayList<Map>();

		for (Map clip : newFeed) {
			String index = clip.get(HistoryDBAdapter.KEY_DB_NO).toString();
			String device = clip.get(HistoryDBAdapter.KEY_DB_DEVICE).toString();
			String date = clip.get(HistoryDBAdapter.KEY_DB_DATE).toString();
			String text = clip.get(HistoryDBAdapter.KEY_DB_TEXT).toString();
			String content = clip.get(HistoryDBAdapter.KEY_DB_CONTENTS)
					.toString();
			String keep = clip.get(HistoryDBAdapter.KEY_DB_KEEPBOX).toString();
			String imageUrls = clip.get(HistoryDBAdapter.KEY_DB_IMG).toString();

			// HISTORY_IMG_URL, HISTORY_IMG_PATH, ORDER
			List<String> order = new ArrayList<String>();
			List<String> imageUrlList = new ArrayList<String>();
			List<String> imagePathList = new ArrayList<String>();

			// image url은 , 로 분리
			if (imageUrls.contains(", ")) {
				String[] splitStr = imageUrls.split(", ");
				for (int i = 0; i < splitStr.length; i++) {
					String imageUrl = splitStr[i];
					imageUrl = imageUrl.substring(imageUrl.indexOf("\"") + 1,
							imageUrl.lastIndexOf("\""));
					imageUrlList.add(GetDataFromApi.IMAGE_SERVER + imageUrl);
					Log.i("clip", "data1=" + imageUrls);
				}
			} else if (!imageUrls.equals("")) {
				String imageUrl = imageUrls;
				imageUrl = imageUrl.substring(imageUrl.indexOf("\"") + 1,
						imageUrl.lastIndexOf("\""));
				imageUrlList.add(GetDataFromApi.IMAGE_SERVER + imageUrl);
				Log.i("clip", "data2=" + imageUrls);
			}

			// image local SD path
			for (int j = 0; j < imageUrlList.size(); ++j) {
				String imgPath = GlobalValue.CLIPPICK_IMAGE_ROOT_FOLDER
						+ File.separator + index + "_" + j + ".jpg";

				imgPath = Utils.downloadFromUrl(imageUrlList.get(j), index
						+ "_" + j, GlobalValue.CLIPPICK_IMAGE_ROOT_FOLDER);
				imagePathList.add(imgPath);
			}

			// get [img0] order
			for (int i = 0; i < imagePathList.size(); ++i) {
				String splitWord = "[img" + i + "]";

				if (content.contains(splitWord)) { // 자르는 단어 있는 경우
					int index1 = content.indexOf(splitWord); // 위치

					// 맨앞에 없는 경우
					if (index1 != 0) {
						String preWord = content.substring(0, index1);
						preWord = preWord.replace("\r\n", "\n");
						order.add(preWord);
						content = content.substring(index1);
					}

					index1 = splitWord.length();
					String preWord = content.substring(0, index1);
					preWord = preWord.replace("\r\n", "\n");
					order.add(preWord);
					content = content.substring(index1);
				}
			}

			if (!content.equals("")) {
				content = content.replace("\r\n", "\n");
				order.add(content);
			}

			// set new data
			clip.put(HistoryDBAdapter.KEY_DB_NO, index);
			clip.put(HistoryDBAdapter.KEY_DB_DEVICE, device);
			clip.put(HistoryDBAdapter.KEY_DB_DATE, date);
			clip.put(HistoryDBAdapter.KEY_DB_TEXT, text);
			clip.put(HistoryDBAdapter.KEY_DB_CONTENTS, content);
			clip.put(HistoryDBAdapter.KEY_DB_IMG, imageUrls);
			clip.put(HistoryDBAdapter.KEY_DB_KEEPBOX, keep);
			clip.put("HISTORY_IMG_ORDER", order);
			clip.put("HISTORY_IMG_URLS", imageUrlList);
			clip.put("HISTORY_IMG_PATH", imagePathList);
			result.add(clip);
		}
		return result;
	}
}
